package com.ch08.controller;

import com.ch08.controller.vo.ResultVO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/**
 * @ClassName UploadController
 * @Description 文件上传
 * @Author Kx
 * @Date 2025/5/15 15:36
 * @Version 1.0
 */
@RestController
public class UploadController extends BaseController {
    /**
     * @author: kx
     * @date: 2025/5/15 15:40
     * @param files : 文件数组对象
     * @return com.ch08.controller.vo.ResultVO
     * @description:
    */
    @PostMapping("/upload")
    public ResultVO upload(@RequestParam("files") MultipartFile[] files) throws IOException {
        // 获取上传目录
        File uploadDir = new File("D:/upload");
        // 判断是否存在此目录
        if (!uploadDir.exists()) {
            // 创建此目录
            uploadDir.mkdirs();
        }
        // 循环文件数组
        for (MultipartFile file : files) {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            // 获取文件大小
            long fileSize = file.getSize();
            System.out.println(fileSize);
            // 获取文件类型
            String contentType = file.getContentType();
            System.out.println(contentType);
            // 获取文件绝对路径
            String absolutePath = uploadDir.getAbsolutePath();

            // 构建上传路径
            Path path = FileSystems.getDefault().getPath(absolutePath, fileName);
            // 上传文件
            file.transferTo(path);
        }
        return success();
    }
}
